package com.ruoyi.utils.aly;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.cdn20180510.Client;
import com.aliyun.cdn20180510.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.SSL.domain.SslApply;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;

import java.util.List;

/**
 * 阿里云cdn域名接口类
 */
public class AlyCDNDomainApiUtils {

    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.accessKeyId = accessKeyId.trim();
        config.accessKeySecret = accessKeySecret.trim();
        config.setAccessKeyId(accessKeyId.trim());
        config.setAccessKeySecret(accessKeySecret.trim());
        config.endpoint = "cdn.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 查询cdn域名数据的方法
     * @param accessKeyId keyId
     * @param accessKeySecret 秘钥
     * @return 返回查询到的数据
     */
    public static AjaxResult selectCDNDmoainList(String accessKeyId, String accessKeySecret){
        try {
            //获取到客户端请求对象
            Client client = createClient(accessKeyId, accessKeySecret);
            //查询域名
            RuntimeOptions runtime = new RuntimeOptions();
            DescribeUserDomainsRequest userDomainsRequest = new DescribeUserDomainsRequest();
            DescribeUserDomainsResponse userDomainsResponse = client.describeUserDomainsWithOptions(userDomainsRequest, runtime);
            //判断请求状态
            if(userDomainsResponse.getStatusCode() == 200){
                //得到数据
                List<DescribeUserDomainsResponseBody.DescribeUserDomainsResponseBodyDomainsPageData> dataList = userDomainsResponse.getBody().getDomains().getPageData();
                return AjaxResult.success("查询阿里云CDN域名列表成功！", dataList);
            }else{
                return AjaxResult.error("查询阿里云CDN域名列表失败："+JSONUtil.toJsonStr(userDomainsResponse.getBody()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询阿里云CDN域名列表失败：", e.getMessage());
        }
    }


    public static AjaxResult selectSSLByDomain(String accessKeyId, String accessKeySecret, String domainTxt){
        try {
            //获取到客户端请求对象
            Client client = createClient(accessKeyId, accessKeySecret);
            //查询域名
            RuntimeOptions runtime = new RuntimeOptions();
            DescribeDomainCertificateInfoRequest describeDomainCertificateInfoRequest = new DescribeDomainCertificateInfoRequest();
            describeDomainCertificateInfoRequest.setDomainName(domainTxt);
            DescribeDomainCertificateInfoResponse describeDomainCertificateInfoResponse = client.describeDomainCertificateInfoWithOptions(describeDomainCertificateInfoRequest, runtime);
            //判断请求状态
            if(describeDomainCertificateInfoResponse.getStatusCode() == 200){
                //得到数据
                List<DescribeDomainCertificateInfoResponseBody.DescribeDomainCertificateInfoResponseBodyCertInfosCertInfo> dataList = describeDomainCertificateInfoResponse.getBody().getCertInfos().getCertInfo();
                return AjaxResult.success("查询阿里云CDN域名的证书成功！", dataList);
            }else{
                return AjaxResult.error("查询阿里云CDN域名的证书失败："+JSONUtil.toJsonStr(describeDomainCertificateInfoResponse.getBody()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询阿里云CDN域名的证书失败：", e.getMessage());
        }
    }

    /**
     * 配置cdn证书的方法
     * @param accessKeyId 阿里云keyId
     * @param accessKeySecret 阿里云秘钥
     * @return 返回配置成功与否
     */
    public static AjaxResult setCDNDomainCSR(String accessKeyId, String accessKeySecret, SslApply sslApply, String domainTxt, String ptName){
        try {
            Client client = createClient(accessKeyId, accessKeySecret);
            //执行替换操作
            RuntimeOptions runtime = new RuntimeOptions();
            BatchSetCdnDomainServerCertificateRequest certificateRequest = new BatchSetCdnDomainServerCertificateRequest();
            //赋值参数
            String[] fileArray = sslApply.getSslFilePath().split(",");
            certificateRequest.domainName=domainTxt;
            certificateRequest.certName=sslApply.getCertificateDomain()+"_"+ptName+"_"+ RandomUtil.randomStringUpper(9);
            certificateRequest.certType="upload";
            certificateRequest.SSLProtocol="on";        //启用https证书
            certificateRequest.SSLPub = FileUtils.readFileContent(fileArray[1]);
            certificateRequest.SSLPri = FileUtils.readFileContent(fileArray[0]);
            BatchSetCdnDomainServerCertificateResponse certificateResponse = client.batchSetCdnDomainServerCertificateWithOptions(certificateRequest, runtime);
            //判断是否配置成功
            if(certificateResponse.getStatusCode() == 200){
                return AjaxResult.success("配置阿里云CDN证书成功！");
            }else{
                return AjaxResult.error("配置阿里云CDN证书失败："+JSONUtil.toJsonStr(certificateResponse.getBody()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("配置阿里云CDN证书失败："+ e.getMessage());
        }
    }
}
